<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- Tabs 标签页 -->
        <el-tabs v-model="activeName" class="tabNav">
          <el-tab-pane label="组织架构" name="first" />
        </el-tabs>
        <div class="tree-card">
          <!-- 标题 -->
          <TreeTools
            :tree-node="company"
            :is-root="true"
            @addDepts="addDepts"
          />
          <hr>
          <el-tree :data="departs" :props="defaultProps" default-expand-all>
            <!-- 传入内容 插槽内容 会循环多次 有多少节点 就循环多少次 -->
            <!-- 作用域插槽 slot-scope="obj" 接收传递给插槽的数据   data 每个节点的数据对象-->
            <TreeTools
              slot-scope="{ data }"
              :tree-node="data"
              @addDepts="addDepts"
              @delDepts="getDepartments"
              @editDepts="editDepts"
            />
          </el-tree>
        </div>
      </el-card>
      <!-- // 父组件 sync修饰符,只要用sync修饰，就可以省略父组件的监听和方法，直接将值赋值给showDialog -->
      <AddDept
        ref="addDept"
        :show-dialog.sync="showDialog"
        :node="node"
        @addDepts="getDepartments"
      />
    </div>
  </div>
</template>

<script>
import TreeTools from './components/tree-tools'
import { getDepartments } from '@/api/departments'
import { transListToTreeData } from '@/utils'
import AddDept from './components/add-dept'
export default {
  components: {
    TreeTools,
    AddDept
  },
  data() {
    return {
      activeName: 'first',
      company: {
        name: '江苏传智播客教育科技股份有限公司',
        manager: '负责人',
        id: ''
      },
      departs: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showDialog: false,
      node: {}
    }
  },
  created() {
    // const res = await getDepartments()
    // console.log(res)
    // this.departs = transListToTreeData(res.depts, '')
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      const res = await getDepartments()
      console.log(res)
      this.departs = transListToTreeData(res.depts, '')
    },
    addDepts(treeNode) {
      console.log('子组件点击新增触发,获取到被点击的那个组件的数据')
      console.log(treeNode)
      // 1. 控制弹窗
      this.showDialog = true
      // 2. 将获取的 treeNode 传给弹窗
      this.node = treeNode
    },
    async editDepts(treeNode) {
      // console.log(2)
      // 除弹窗外,还需要执行子组件获取数据方法  来实现数据回显
      // 我们可以在调用**编辑方法** **`editDepts`**中通过**`ref`**调用**`add-dept.vue`**的实例方法
      await this.$refs.addDept.getDepartDetail(treeNode.id) // 直接调用子组件中的方法 传入一个id
      this.showDialog = true // 显示新增组件弹层
      this.node = treeNode // 存储传递过来的node数据
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 20px 140px;
  font-size: 16px;
}
.tabNav {
  padding: 13px 0px 0 35px;
}
</style>
